/** 
*  手册/程序
*/
<template>
  <el-form v-loading="loading"  :model="formData" :rules="type == 'add' || type == 'edit' || type =='reedit' || type === 'revision'? formRules : {}" ref="formRef" label-width="120px" :scroll-to-error="true">
    <vp-card>
      <el-row>
        <vp-col :span="4">
            <el-form-item prop="bh">
              <template #label><vp-label zh="记录单号" en="Rec. No."/></template>
                  <el-input v-model="formData.bh" readonly placeholder="自动生成/Auto-Generate" v-if="type === 'add' || type === 'edit' || type === 'revision'" maxlength="50">
                  </el-input>
                  <span v-else>{{ formData.bh }}</span>
            </el-form-item>
        </vp-col>
      </el-row>
    </vp-card>
    <vp-card>
      <template #header><vp-label zh="手册程序信息" en="Manual Procedure Information"/></template>
      <el-row>
        <vp-col :span="2">
            <el-form-item prop="xdlx">
              <template #label><vp-label zh="修订类型" en="Rev. Type"/></template>
                <el-radio-group  v-model="formData.xdlx"  v-if="type === 'add' || type === 'edit' || type === 'revision'" @change="handleChangeXdlx">
                  <el-radio :label="10" :key="10">{{"新增/Add" }}</el-radio>
                  <el-radio :label="20" :key="20">{{'修订/Revision'}}</el-radio>
                  <el-radio :label="30" :key="30">{{'删除/Delete'}}</el-radio>
                </el-radio-group>
                <span v-else>{{ formData.xdlx == 10 ? "新增/Add" : formData.xdlx == 20 ? '修订/Revision' : 
                  formData.xdlx == 30 ? '删除/Delete' :  "" }}</span>
            </el-form-item>
        </vp-col>
        <vp-col :span="2">
            <el-form-item prop="wjlx">
              <template #label><vp-label zh="文件类型" en="Rev. Type"/></template>
                <el-radio-group  v-model="formData.wjlx"  v-if="type === 'add' || type === 'edit'|| type === 'revision'" @change="handleChangeWjlx" >
                  <el-radio :label="20" :key="20">{{'工作程序/Work Procedure'}}</el-radio>
                  <el-radio :label="10" :key="10">{{"手册/Manual" }}</el-radio>
                  <el-radio :label="30" :key="30">{{'表格/Table'}}</el-radio>
                </el-radio-group>
                <span v-else>{{ formData.wjlx == 10 ? "手册/Manual" : formData.wjlx == 20 ? '工作程序/Work Procedure' : 
                  formData.wjlx == 30 ? '表格/Table' :  ""
                   }}</span>
            </el-form-item>
        </vp-col>
      </el-row>
      <template v-if="formData.wjlx">
      <el-row >
        <vp-col :span="4" v-if="formData.wjlx == 30">
            <el-form-item prop="ssgzcx">
              <template #label><vp-label zh="所属工作程序" en="AWP"/></template>
                  <el-input v-model="formData.ssgzcx" readonly v-if="(type === 'add' || type === 'edit' || type =='reedit' || type === 'revision') " >
                    <template #append>
                      <el-button @click="handleChooseAWP"><SvgIcon name="ele-Search" /></el-button>
                    </template>
                  </el-input>
                <span v-else>{{ formData.ssgzcx }}</span>
            </el-form-item>
        </vp-col>
        <vp-col :span="4">
            <el-form-item prop="wjbh">
              <template #label><vp-label zh="编号" en="No."/></template>
                  <el-input v-model="formData.wjbh" :readonly="formData.xdlx == 20 || formData.xdlx == 30" v-if="type === 'add' || type === 'edit' || type =='reedit' || type === 'revision'" maxlength="100">
                    <template #append v-if="formData.xdlx == 20 || formData.xdlx == 30">
                      <el-button @click="handleChooseBh"><SvgIcon name="ele-Search" /></el-button>
                    </template>
                  </el-input>
                <span v-else>{{ formData.wjbh }}</span>
            </el-form-item>
        </vp-col>
        <vp-col :span="2">
          <el-space>
            <div>
              <el-form-item prop="bcXdh" v-if="formData.xdlx == 10 || formData.xdlx == 20">
                <template #label><vp-label zh="版次" en="Edition"/></template>
                    <el-input v-model="formData.bcXdh" v-if="(type === 'add' || type === 'edit' || type =='reedit'|| type === 'revision') && (formData.xdlx == 20 || formData.xdlx == 10) " maxlength="100">
                    </el-input>
                  <span v-else>{{ formData.bcXdh }}</span>
              </el-form-item>
              <el-form-item prop="bcXdq" v-if="formData.xdlx == 30">
                <template #label><vp-label zh="版次" en="Edition"/></template>
               </el-form-item> 
            </div>
            <div v-if="formData.xdlx == 20 || formData.xdlx == 30" style="display: flex;">
              <SvgIcon name="ele-Back" v-if="formData.xdlx == 20 && formData.bcXdq" />
              <span > {{ formData.bcXdq }}</span>
            </div>
          </el-space>
        </vp-col>
      </el-row>
      <el-row>
        <vp-col :span="1">
            <el-form-item prop="wjbh">
              <template #label><vp-label zh="标题" en="Title"/></template>
                  <el-input v-model="formData.bt" v-if="(type === 'add' || type === 'edit' ||type =='reedit'|| type === 'revision') && formData.xdlx == 10" maxlength="100">
                  </el-input>
                <span v-else>{{ formData.bt }}</span>
            </el-form-item>
        </vp-col>
      </el-row>
      <el-row>
        <vp-col :span="4" v-if="formData.xdlx == 20 || formData.xdlx == 10">
            <el-form-item prop="sxrqXdh">
              <template #label><vp-label zh="生效日期" en="Effective Date"/></template>
                <el-date-picker
                  v-model="formData.sxrqXdh"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder=""
                  v-if="type === 'add' || type === 'edit' || type =='reedit'|| type === 'revision'"
                  class="w100"
                ></el-date-picker>
                <span v-else>{{ formData.sxrqXdh }}</span>
            </el-form-item>
        </vp-col>
        <vp-col :span="4" v-if="formData.xdlx == 30">
            <el-form-item prop="sxrqXdq">
                <template #label><vp-label zh="生效日期" en="Effective Date"/></template>
                <span >{{ formData.sxrqXdq }}</span>
            </el-form-item>
        </vp-col>
        <vp-col :span="4" v-if="formData.xdlx == 20">
            <el-form-item :label="$t('item.attachment')" prop="attachmentXdqs">
                  <template #label><vp-label zh="修订前文件" en="PRD" align="left"/></template>
                  <RowAttachment :readOnly="true" v-model:attachmentList="formData.attachmentXdqs" ></RowAttachment>
              </el-form-item>
        </vp-col>
        <vp-col :span="4" v-if="formData.xdlx == 30">
            <el-form-item :label="$t('item.attachment')" prop="attachmentXdqs">
                  <template #label><vp-label zh="文件" en="File" align="left"/></template>
                  <RowAttachment :readOnly="true" v-model:attachmentList="formData.attachmentXdqs" ></RowAttachment>
              </el-form-item>
        </vp-col>
        <vp-col :span="4" v-if="formData.xdlx == 20 || formData.xdlx == 10">
            <el-form-item :label="$t('item.attachment')" prop="attachmentXdhs">
                <template #label><span class="required" v-if="type == 'add' || type == 'edit' || type =='reedit' || type === 'revision'"></span><vp-label zh="文件" en="File" align="left"/></template>
                <RowAttachment :readOnly="!(type === 'add' || type === 'edit' || type =='reedit' || type === 'revision')" v-model:attachmentList="formData.attachmentXdhs" @attachmentListEmit="getAttachmentListEmit($event,formData)"></RowAttachment>
            </el-form-item>
        </vp-col>
      </el-row>
    </template>
    </vp-card>
    <vp-card v-if="formData.wjlx == 20 && (formData.xdlx == 10 || formData.xdlx == 20)">
      <template #header><vp-label zh="表格" en="Table"/></template>
      <el-row>
        <vp-table ref="tableRef" :data="formData.tables" row-key="id" max-height="350px" >
          <el-table-column  type="index" align="center" label="#"></el-table-column>
          <el-table-column  prop="bh" min-width="150" show-overflow-tooltip >
            <template #header><vp-label zh="编号" en="No."/></template>
            <template #default="scope">
              <el-form-item :prop="`tables[${scope.$index}].bh`"  :rules="formRules.tables.bh" label-width="auto">
                <el-input v-if="(type === 'add' || type === 'edit' ||type =='reedit'|| type === 'revision') && scope.row.xdlx == 10" v-model="scope.row.bh" v-trim maxlength="100"  >
                </el-input>
                  <span v-else >{{ scope.row.bh }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column  prop="bt" min-width="200" show-overflow-tooltip >
            <template #header><vp-label zh="标题" en="Title."/></template>
            <template #default="scope">
              <el-form-item :prop="`tables[${scope.$index}].bt`"  :rules="formRules.tables.bt" label-width="auto">
                <el-input v-if="(type === 'add' || type === 'edit' || type =='reedit' || type === 'revision')&& scope.row.xdlx == 10" v-model="scope.row.bt" v-trim maxlength="100"  >
                </el-input>
                  <span v-else >{{ scope.row.bt }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column   show-overflow-tooltip align="center" v-if="formData.xdlx == 20">
              <template #header><vp-label zh="修订前" en="Pre-Rev."/></template>
              <el-table-column  prop="bcXdq" min-width="70" show-overflow-tooltip >
                  <template #header><vp-label zh="版次" en="Edition"/></template>
                  <template #default="scope">
                        <span >{{ scope.row.bcXdq }}</span>
                  </template>
                </el-table-column>
                <el-table-column  prop="sxrqXdq" min-width="120" show-overflow-tooltip >
                  <template #header><vp-label zh="生效日期" en="Effective Date"/></template>
                  <template #default="scope">
                      <span >{{ scope.row.sxrqXdq }}</span>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('personalArchive.fj')" min-width="180">
                    <template #header><vp-label zh="附件" en="File"/></template>
                    <template #default="scope">
                        <RowAttachment :attachmentList="scope.row.attachmentXdqs" :readOnly="true"></RowAttachment>
                      </template>
                </el-table-column>
          </el-table-column>
          <el-table-column  prop="bcXdh" min-width="100" show-overflow-tooltip >
            <template #header><span class="required" v-if="type == 'add' || type == 'edit' || type =='reedit' || type === 'revision'"></span><vp-label zh="版次" en="Edition"/></template>
            <template #default="scope">
                <el-input v-if="(type === 'add' || type === 'edit' || type =='reedit'|| type === 'revision') && (scope.row.xdlx == 10 || scope.row.xdlx == 20)" v-model="scope.row.bcXdh" v-trim maxlength="100"  >
                </el-input>
                  <span v-else >{{ scope.row.bcXdh }}</span>
            </template>
          </el-table-column>
          <el-table-column  prop="sxrqXdh" min-width="150" show-overflow-tooltip >
            <template #header><span class="required" v-if="type == 'add' || type == 'edit' || type =='reedit' || type === 'revision'"></span><vp-label zh="生效日期" en="Effective Date"/></template>
            <template #default="scope">
                <el-date-picker
                  v-model="scope.row.sxrqXdh"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder=""
                  v-if="(type === 'add' || type === 'edit' || type =='reedit'|| type === 'revision') && (scope.row.xdlx == 10 || scope.row.xdlx == 20)"
                  class="w100"
                ></el-date-picker>
                <span v-else>{{ scope.row.sxrqXdh }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('personalArchive.fj')" min-width="180">
              <template #header><span class="required" v-if="type == 'add' || type == 'edit' || type =='reedit' || type === 'revision'"></span><vp-label zh="附件" en="File"/></template>
              <template #default="scope">
                  <RowAttachment :attachmentList="scope.row.attachmentXdhs" :readOnly="!((type === 'add' || type === 'edit' || type =='reedit'|| type === 'revision') && (scope.row.xdlx == 10 || scope.row.xdlx == 20))"
                    @attachmentListEmit="getAttachmentListEmit($event, scope.row)"></RowAttachment>
                </template>
          </el-table-column>
          <el-table-column  prop="xdlx" min-width="150" show-overflow-tooltip v-if="formData.xdlx == 20">
            <template #header><vp-label zh="修订类型" en="Rev. Type"/></template>
            <template #default="scope">
                  <el-select class="w100" v-model="scope.row.xdlx" v-if="(type === 'add' || type === 'edit'|| type == 'reedit'|| type === 'revision') && scope.row.bcXdq" @change="handleChangeRowWjlx(scope.row)" >
                    <el-option :value="20" label="修订/Revision"></el-option>
                    <el-option :value="30" label="删除/Delete"></el-option>
                    <el-option :value="40" label="不修订/No Revision"></el-option>
							</el-select>
                <span v-else>{{ scope.row.xdlx == 10 ? "新增/Add" : scope.row.xdlx == 20 ? '修订/Revision' : 
                  scope.row.xdlx == 30 ? '删除/Delete' : scope.row.xdlx == 40 ? '不修订/No Revision' : "" }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" v-if="type == 'add' || type == 'edit' || type =='reedit'|| type === 'revision' " fixed="right">
              <template #header>
                  <el-button circle @click="handleAddTable()"><SvgIcon name="ele-Plus"></SvgIcon></el-button>
              </template>
              <template #default="scope" >
                  <el-button v-if="!scope.row.bcXdq" circle @click="handleDeleteTable(scope.$index)"><SvgIcon name="ele-Minus"></SvgIcon></el-button>
              </template>
          </el-table-column>
        </vp-table>
      </el-row>
    </vp-card>
    <vp-card v-if="formData.wjlx">
      <el-row class="mt8" v-if="formData.xdlx != 30">
          <vp-col :span="1">
            <el-form-item prop="bmms">
              <template #label><vp-label zh="涉及部门" en="Involved Dept."/></template>
                  <el-input v-model="formData.bmms" readonly v-if="type === 'add' || type === 'edit' || type == 'reedit'|| type === 'revision'" >
                    <template #append>
                      <el-button @click="chooseDepartment"><SvgIcon name="ele-Search" /></el-button>
                    </template>
                  </el-input>
                <span v-else>{{ formData.bmms }}</span>
            </el-form-item>
          </vp-col>
        </el-row>
        <el-row>
        <vp-col :span="1">
					<el-form-item prop="xdnrms">
						<template #label><vp-label zh="修订内容描述" en="RCD" align="left"/></template>
						<el-input type="textarea" v-if="type == 'add' || type == 'edit' || type == 'reedit'|| type === 'revision'" v-model="formData.xdnrms" v-trim maxlength="1000" rows="3"></el-input>
            <span v-else  style="white-space:pre">{{ formData.xdnrms }}</span>
          </el-form-item>
				</vp-col>
      </el-row>
    </vp-card>
  	<VpDepartmentMultDialog ref="departmentMultDialogRef" @confirm="handleChooseDepartment"></VpDepartmentMultDialog>
  	<VpManualDialog ref="manualDialogRef" ></VpManualDialog>
  </el-form>
</template>
<script setup lang="ts" name="QualityManualCommon">
import { computed, defineAsyncComponent, onMounted, ref, watch } from "vue";
import request from "/@/utils/request";
import validateUtils from "/@/utils/validateUtils";
import { ElMessage } from "element-plus";
import RowAttachment from '/@/components/vp/file/VpRowAttachment.vue';

const VpDepartmentMultDialog = defineAsyncComponent(() => import('/@/components/vp/department/VpDepartmentMultDialog.vue'));
const VpManualDialog = defineAsyncComponent(() => import('/@/components/vp/manual/VpManualDialog.vue'));

const emits = defineEmits(['formSubmited']);

  const formData = ref({
      id:"",
      bh: "",
      xdlx: null as any,
      wjlx: null,
      ssgzcxid: "",
      ssgzcx: "",
      wjid: "",
      wjbh: "",
      bt: "",
      bcXdq: "",
      bcXdh: "",
      sxrqXdq: "",
      sxrqXdh: "",
      xdnrms: "",
      fjglidXdq: "",
      fjglidXdh: "",
      tables: [],
      depts: [],
      attachmentXdqs: [],
      attachmentXdhs: [],
  });
  const formRules = {
      xdlx: [
        validateUtils.notNull,
      ],
      wjlx: [
        validateUtils.notNull,
      ],
      wjbh: [
        validateUtils.notNull,
      ],
      bcXdh: [
        validateUtils.notNull,
      ],
      bt: [
        validateUtils.notNull,
      ],
      sxrqXdh: [
        validateUtils.notNull,
      ],
      ssgzcx: [
        validateUtils.notNull,
      ],
      attachmentXdhs: [
        {
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error('请上传文件/Please upload the file')) 
            } else {
              callback()
            }
          },
        }
      ],
      tables: {
        bh: [
          validateUtils.notNull,
        ],
        bt: [
          validateUtils.notNull,
        ],
      },
  }

  const initFormData = () =>{
      formData.value = {
        id:"",
        bh: "",
        xdlx: null,
        wjlx: null,
        ssgzcxid: "",
        ssgzcx: "",
        wjid: "",
        wjbh: "",
        bt: "",
        bcXdq: "",
        bcXdh: "",
        sxrqXdq: "",
        sxrqXdh: "",
        xdnrms: "",
        fjglidXdq: "",
        fjglidXdh: "",
        tables: [],
        depts: [],
        attachmentXdqs: [],
        attachmentXdhs: [],
      }
  }

  const type = ref('add');
  const loading = ref(false);
  const formRef = ref();

  const props = defineProps<{
    id: string,
    type: string,
    ny: string,
  }>()

  onMounted(() => {
    handleOpen(props.type, props.id, props.ny);
  })

  const handleOpen = (_type: string, id: string, ny:string) =>{
      initFormData();
      type.value = _type;
      if(type.value == 'revision'){
        loadDetail(id);
        formData.value.xdlx = 20;
      }else if (type.value != "add") {
        loading.value = true;
        request.get(`/quality/manual/${id}`).then((res) => {
          formData .value= {
            ...formData.value,
            ...res.data,
            bmms: (res.data.depts||[]).map((obj:any) => {return obj.bmmc}).join(",")
          };
          loading.value = false;
          emits("formSubmited", formData.value);
        });
      }else {
        formData.value.xdlx = 10;
      }
    }

    const manualDialogRef = ref();

   const handleChooseAWP = () =>{
    manualDialogRef.value.handleOpen({
      selectedId: formData.value.ssgzcxid,
      lx: 20,
      callback: function(data: any){
        formData.value.ssgzcxid = data.id;
        formData.value.ssgzcx = data.bh;
      }
    })
   } 

   const handleChangeXdlx = () =>{
      emptyData();
   }

   const emptyData = () =>{
      formData.value.wjid = "";
      formData.value.wjbh = "";
      formData.value.bcXdq = "";
      formData.value.bcXdh = "";
      formData.value.sxrqXdq =  "";
      formData.value.fjglidXdq = "";
      formData.value.fjglidXdh = "";
      formData.value.bt = "";
      formData.value.ssgzcxid = "";
      formData.value.ssgzcx = "";
      formData.value.attachmentXdqs = [];
      formData.value.attachmentXdhs = [];
      formData.value.tables = [];
   }

   const handleChangeWjlx = () =>{
    if(formData.value.xdlx === 10){
      formData.value.ssgzcxid = "";
      formData.value.ssgzcx = "";
    }else {
      emptyData();
    }
   }

   const handleChooseBh = () => {
      if(!formData.value.wjlx) {
          return;
      }
      if(formData.value.wjlx == 30 && ! formData.value.ssgzcxid ){
        return;
      }
      manualDialogRef.value.handleOpen({
        selectedId: formData.value.wjid,
        lx: formData.value.wjlx,
        ssgzcxid: formData.value.ssgzcxid,
        callback: function(data: any){
          formData.value.wjid = data.id;
          formData.value.wjbh = data.bh;
          loadDetail(data.id);
        }
      })
   }

   const loadDetail = (id: string) =>{
      if(id){
        loading.value = true;
        request.get(`/quality/manual/list/${id}`).then((res) => {
            formData.value.wjid = res.data.id;
            formData.value.wjbh = res.data.bh;
            formData.value.bcXdq = res.data.bc;
            formData.value.sxrqXdq = res.data.sxrq;
            formData.value.fjglidXdq = res.data.fjglid;
            formData.value.bt = res.data.bt;
            formData.value.attachmentXdqs = res.data.attachments;
            formData.value.wjlx = res.data.lx;
            formData.value.ssgzcx = res.data.ssgzcx;
            formData.value.ssgzcxid = res.data.ssgzcxid;
            if(res.data.tables && res.data.tables.length > 0){
              formData.value.tables = (res.data.tables).map((table:any) =>{
                return {
                   wjid: table.id,
                   bh: table.bh,
                   bt: table.bt,
                   bcXdq: table.bc,
                   sxrqXdq: table.sxrq,
                   fjglidXdq: table.fjglid,
                   attachmentXdqs: table.attachments,
                   xdlx: 20,
                }
              })
            }
            loading.value = false;
        });
      }else {
        emptyData();
      }
   }

  const handleAddTable = () =>{
      formData.value.tables.push({xdlx: 10});
    }

  const handleDeleteTable = (index: number)=>{
      formData.value.tables.splice(index, 1);
  }

  const handleChangeRowWjlx = (row: any) =>{
    row.sxrqXdh= "";
    row.bcXdh ="";
    row.attachmentXdhs = [];
  }

  const getAttachmentListEmit = (list : any, row: any) =>{
    row.attachmentXdhs = list;
  }

  const departmentMultDialogRef = ref();

  const chooseDepartment = () =>{
		departmentMultDialogRef.value.handleOpen();
	}

	const handleChooseDepartment = (data: any) =>{
		let bms = data.map((item: any) => item.dprtname).join(',');
    let dprts = data.map((item:any) =>{
      return {bmid: item.id, bmmc: item.dprtname} 
    })
		formData.value.depts = dprts;
		formData.value.bmms = bms;
	}


  const getData = (zt: number): Promise<any> => {
        let promise = new Promise((resolve, reject) => {
          if(zt == 10){
            resolve({
                ...formData.value,
              });
          }
          formRef.value.validate((valid: boolean) => {
              if (valid) {
                if(formData.value.tables.length > 0){
                  let bhList = [] as any[];
                  formData.value.tables.forEach((obj:any)=>{
                    if(!obj.sxrqXdh && (obj.xdlx ==10 || obj.xdlx == 20)){
                      ElMessage.error('表格中生效日期不能为空/The effective date cannot be empty');
                      reject();
                    }
                    if(!obj.bcXdh && (obj.xdlx ==10 || obj.xdlx == 20)){
                      ElMessage.error('表格中版次不能为空/The edition cannot be empty');
                      reject();
                    }
                    if((!obj.attachmentXdhs || obj.attachmentXdhs.length == 0) && (obj.xdlx ==10 || obj.xdlx == 20)){
                      ElMessage.error('表格中附件不能为空/The File cannot be empty');
                      reject();
                    }
                    if(bhList.indexOf(obj.bh) > -1){
                      ElMessage.error('表格编号存在重复/There are duplicate numbers');
                      reject();
                    }else{
                      bhList.push(obj.bh);
                    }
                  })
                }
                resolve({
                  ...formData.value,
                });
              } else {
                  reject();
              }
          })  
        })
        return promise;
      };



defineExpose({
  getData
})

</script>
<style scoped lang="scss">
	.required:before {
		content: "*";
		color: var(--el-color-danger);
		margin-right: 4px;
	}
</style>
